package work.linruchang.mybatisplussamplestest.config.mybatisplus.injector;

import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.methods.DeleteById;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

import java.util.List;

import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

/**
 * 作用：逻辑删除
 *  照抄官方{@link DeleteById}
 * @author LinRuChang
 * @version 1.0
 * @date 2022/06/14
 * @since 1.8
 **/
public class DeleteByIdLogic extends AbstractMethod {
    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {

        boolean withLogicDelete = tableInfo.isWithLogicDelete();

        //当前表支持逻辑删除，不支持则不注入
        if(withLogicDelete) {
            String sql;
            SqlMethod sqlMethod = SqlMethod.LOGIC_DELETE_BY_ID;
            List<TableFieldInfo> fieldInfos = tableInfo.getFieldList().stream()
                    .filter(TableFieldInfo::isWithUpdateFill)
                    .filter(f -> !f.isLogicDelete())
                    .collect(toList());
            if (CollectionUtils.isNotEmpty(fieldInfos)) {
                String sqlSet = "SET " + SqlScriptUtils.convertIf(fieldInfos.stream()
                        .map(i -> i.getSqlSet(EMPTY)).collect(joining(EMPTY)), "!@org.apache.ibatis.type.SimpleTypeRegistry@isSimpleType(_parameter.getClass())", true)
                        + tableInfo.getLogicDeleteSql(false, false);
                sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), sqlSet, tableInfo.getKeyColumn(),
                        tableInfo.getKeyProperty(), tableInfo.getLogicDeleteSql(true, true));
            } else {
                sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(), sqlLogicSet(tableInfo),
                        tableInfo.getKeyColumn(), tableInfo.getKeyProperty(),
                        tableInfo.getLogicDeleteSql(true, true));
            }
            SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, Object.class);
            //return addUpdateMappedStatement(mapperClass, modelClass, getMethod(sqlMethod), sqlSource);
            return addUpdateMappedStatement(mapperClass, modelClass, "deleteByIdLogic", sqlSource);
        }

        //无逻辑删除字段，则不注入上述SQL,当调用work.linruchang.mybatisplussamplestest.dao.MyBaseMapper.deleteByIdLogic(java.io.Serializable)会报异常
        return null;
    }
}
